package com.study.project.realm;

import com.study.project.entity.UserDO;
import com.study.project.service.LoginService;
import com.study.project.service.RolesService;
import com.study.project.service.UserRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
public class MyRealm extends AuthorizingRealm {
    @Resource
    private LoginService loginService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UserRoleService userRoleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取登录信息
        String name = authenticationToken.getPrincipal().toString();
        //查询数据库
        UserDO user = loginService.getUserByName(name);
        //封装信息
        if (Objects.nonNull(user)) {
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPassword(),
                    getName()
            );
            return authenticationInfo;
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1. 获取到登陆成功对象
        String name = (String) principalCollection.getPrimaryPrincipal();
        //2. 查询登陆用户拥有的权限
        List<Integer> roleIds = userRoleService.getRoleIdsByUserId(1);
        List<String> roles = rolesService.getRoleByIds(roleIds);
        //3.把权限添加到AuthorizationInfo对象中，这个对象拥有的权限则代表了当前用户拥有权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //4. 遍历用户的权限，把权限唯一标识添加到authorizationInfo对象里面
        info.addRoles(roles);
//        info.addObjectPermissions();
        return info;
    }

}
